import UIKit

/// 专业相机控制视图
/// 提供 ISO、快门速度和白平衡的专业控制界面
/// 采用点击按钮后显示带刻度滑块的交互方式
class YCCameraControlView: UIView {
    
    // MARK: - Properties
    
    /// ISO 值改变的回调闭包
    var onISOValueChanged: ((Float) -> Void)?
    
    /// 快门速度改变的回调闭包
    var onShutterSpeedValueChanged: ((Float) -> Void)?
    
    /// 白平衡改变的回调闭包
    var onWhiteBalanceValueChanged: ((Float) -> Void)?
    
    /// 当前选中的控制模式
    private var activeControlMode: ControlMode = .none {
        didSet {
            updateControlVisibility()
        }
    }
    
    /// 控制模式枚举
    private enum ControlMode {
        case none
        case iso
        case shutterSpeed
        case whiteBalance
    }
    
    /// 当前参数值
    private var currentISOValue: Float = 0.5
    private var currentShutterValue: Float = 0.5
    private var currentWhiteBalanceValue: Float = 0.5
    
    // MARK: - UI Elements
    
    /// 控制按钮容器视图
    private lazy var controlButtonsContainer: UIStackView = {
        let stack = UIStackView()
        stack.axis = .horizontal
        stack.distribution = .equalSpacing
        stack.alignment = .center
        stack.spacing = 20
        return stack
    }()
    
    /// ISO 控制按钮
    private lazy var isoButton: UIButton = {
        let button = createControlButton(title: "ISO")
        button.addTarget(self, action: #selector(isoButtonTapped), for: .touchUpInside)
        return button
    }()
    
    /// 快门速度控制按钮
    private lazy var shutterButton: UIButton = {
        let button = createControlButton(title: "快门")
        button.addTarget(self, action: #selector(shutterButtonTapped), for: .touchUpInside)
        return button
    }()
    
    /// 白平衡控制按钮
    private lazy var whiteBalanceButton: UIButton = {
        let button = createControlButton(title: "白平衡")
        button.addTarget(self, action: #selector(whiteBalanceButtonTapped), for: .touchUpInside)
        return button
    }()
    
    /// 参数值展示标签
    private lazy var valueLabel: UILabel = {
        let label = UILabel()
        label.textColor = .white
        label.font = .systemFont(ofSize: 14, weight: .medium)
        label.textAlignment = .center
        label.isHidden = true
        return label
    }()
    
    /// 滑块控制容器
    private lazy var sliderContainer: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.7)
        view.layer.cornerRadius = 10
        view.isHidden = true
        return view
    }()
    
    /// 主滑块控制器
    private lazy var mainSlider: UISlider = {
        let slider = UISlider()
        slider.minimumValue = 0
        slider.maximumValue = 1
        slider.addTarget(self, action: #selector(sliderValueChanged(_:)), for: .valueChanged)
        slider.addTarget(self, action: #selector(sliderTouchEnded(_:)), for: [.touchUpInside, .touchUpOutside])
        return slider
    }()
    
    /// 刻度标记容器
    private lazy var tickMarksContainer: UIStackView = {
        let stack = UIStackView()
        stack.axis = .horizontal
        stack.distribution = .equalSpacing
        stack.alignment = .center
        return stack
    }()
    
    /// 刻度值标签容器
    private lazy var tickValuesContainer: UIStackView = {
        let stack = UIStackView()
        stack.axis = .horizontal
        stack.distribution = .equalSpacing
        stack.alignment = .center
        return stack
    }()
    
    // MARK: - Initialization
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Setup
    
    private func setupUI() {
        backgroundColor = UIColor.black.withAlphaComponent(0.5)
        
        // 添加控制按钮容器
        addSubview(controlButtonsContainer)
        controlButtonsContainer.addArrangedSubview(isoButton)
        controlButtonsContainer.addArrangedSubview(shutterButton)
        controlButtonsContainer.addArrangedSubview(whiteBalanceButton)
        
        // 添加滑块容器
        addSubview(sliderContainer)
        sliderContainer.addSubview(mainSlider)
        sliderContainer.addSubview(tickMarksContainer)
        sliderContainer.addSubview(tickValuesContainer)
        
        // 添加值标签
        addSubview(valueLabel)
        
        // 设置约束
        setupConstraints()
        
        // 初始隐藏滑块
        sliderContainer.isHidden = true
        valueLabel.isHidden = true
    }
    
    private func setupConstraints() {
        controlButtonsContainer.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(15)
            make.left.greaterThanOrEqualTo(20)
            make.right.lessThanOrEqualTo(-20)
            make.height.equalTo(40)
        }
        
        valueLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(controlButtonsContainer.snp.bottom).offset(10)
            make.height.equalTo(25)
        }
        
        sliderContainer.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.top.equalTo(valueLabel.snp.bottom).offset(10)
            make.bottom.equalTo(-20)
        }
        
        mainSlider.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.top.equalTo(15)
            make.height.equalTo(30)
        }
        
        tickMarksContainer.snp.makeConstraints { make in
            make.left.equalTo(mainSlider.snp.left)
            make.right.equalTo(mainSlider.snp.right)
            make.top.equalTo(mainSlider.snp.bottom).offset(5)
            make.height.equalTo(10)
        }
        
        tickValuesContainer.snp.makeConstraints { make in
            make.left.equalTo(mainSlider.snp.left)
            make.right.equalTo(mainSlider.snp.right)
            make.top.equalTo(tickMarksContainer.snp.bottom).offset(2)
            make.height.equalTo(15)
        }
    }
    
    // 创建控制按钮的辅助方法
    private func createControlButton(title: String) -> UIButton {
        let button = UIButton(type: .system)
        button.setTitle(title, for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.setTitleColor(.yellow, for: .selected)
        button.titleLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        button.backgroundColor = UIColor.darkGray.withAlphaComponent(0.6)
        button.layer.cornerRadius = 8
        button.contentEdgeInsets = UIEdgeInsets(top: 6, left: 12, bottom: 6, right: 12)
        return button
    }
    
    // MARK: - Control Methods
    
    /// 更新控制可见性
    private func updateControlVisibility() {
        // 重置所有按钮选中状态
        isoButton.isSelected = false
        shutterButton.isSelected = false
        whiteBalanceButton.isSelected = false
        
        // 隐藏滑块和标签
        sliderContainer.isHidden = true
        valueLabel.isHidden = true
        
        // 根据当前模式设置
        switch activeControlMode {
        case .iso:
            isoButton.isSelected = true
            sliderContainer.isHidden = false
            valueLabel.isHidden = false
            setupSliderForISO()
            mainSlider.value = currentISOValue
            updateValueLabel(for: .iso)
            
        case .shutterSpeed:
            shutterButton.isSelected = true
            sliderContainer.isHidden = false
            valueLabel.isHidden = false
            setupSliderForShutterSpeed()
            mainSlider.value = currentShutterValue
            updateValueLabel(for: .shutterSpeed)
            
        case .whiteBalance:
            whiteBalanceButton.isSelected = true
            sliderContainer.isHidden = false
            valueLabel.isHidden = false
            setupSliderForWhiteBalance()
            mainSlider.value = currentWhiteBalanceValue
            updateValueLabel(for: .whiteBalance)
            
        case .none:
            // 全部隐藏
            break
        }
    }
    
    /// 为 ISO 设置滑块
    private func setupSliderForISO() {
        // 清除旧的刻度标记
        clearTickMarks()
        
        // 添加 ISO 刻度标记
        let isoValues = ["50", "100", "200", "400", "800", "1600", "3200"]
        addTickMarks(count: isoValues.count, values: isoValues)
    }
    
    /// 为快门速度设置滑块
    private func setupSliderForShutterSpeed() {
        // 清除旧的刻度标记
        clearTickMarks()
        
        // 添加快门速度刻度标记 - 专业相机常用值，最大值为1秒
        let shutterValues = ["1/4000", "1/2000", "1/1000", "1/500", "1/250", "1/125", "1/60", "1/30", "1/15", "1/8", "1/4", "1/2", "1"]
        
        // 选择合适数量的标记以避免拥挤
        let displayValues = shutterValues.enumerated().filter { index, _ in 
            return index % 2 == 0 || index == shutterValues.count - 1 
        }.map { _, value in value }
        
        addTickMarks(count: displayValues.count, values: displayValues)
    }
    
    /// 为白平衡设置滑块
    private func setupSliderForWhiteBalance() {
        // 清除旧的刻度标记
        clearTickMarks()
        
        // 添加白平衡刻度标记 - 符合用户直觉的描述
        let wbValues = ["暖色调", "阴影", "阴天", "日光", "荧光灯", "冷色调"]
        let temperatures = ["2700K", "3500K", "4500K", "5500K", "6500K", "7500K"]
        
        // 组合两个数组为一个显示数组
        var displayValues: [String] = []
        for (index, name) in wbValues.enumerated() {
            if index < temperatures.count {
                displayValues.append("\(name)\n\(temperatures[index])")
            }
        }
        
        // 添加刻度标记
        addTickMarks(count: displayValues.count, values: displayValues)
    }
    
    /// 清除刻度标记
    private func clearTickMarks() {
        for view in tickMarksContainer.arrangedSubviews {
            view.removeFromSuperview()
        }
        
        for view in tickValuesContainer.arrangedSubviews {
            view.removeFromSuperview()
        }
    }
    
    /// 添加刻度标记
    private func addTickMarks(count: Int, values: [String]) {
        // 添加刻度线
        for _ in 0..<count {
            let tickView = UIView()
            tickView.backgroundColor = .white
            tickView.snp.makeConstraints { make in
                make.width.equalTo(1)
                make.height.equalTo(5)
            }
            tickMarksContainer.addArrangedSubview(tickView)
        }
        
        // 添加刻度值
        for i in 0..<count {
            let valueLabel = UILabel()
            valueLabel.text = values[i]
            valueLabel.textColor = .white
            valueLabel.font = .systemFont(ofSize: 8)
            valueLabel.textAlignment = .center
            tickValuesContainer.addArrangedSubview(valueLabel)
        }
    }
    
    /// 更新值标签
    private func updateValueLabel(for mode: ControlMode) {
        switch mode {
        case .iso:
            // 将 0-1 映射到 ISO 范围 (50-3200)
            let isoValue = 50 * pow(2, 6 * Double(currentISOValue))
            valueLabel.text = "ISO: \(Int(isoValue))"
            
        case .shutterSpeed:
            // 改进的快门速度计算，范围从 1/4000 到 1秒
            let shutterValue = currentShutterValue
            
            // 使用指数映射计算实际快门速度
            let denominator = 4000 * pow(0.5, Double(shutterValue) * 12)
            
            if denominator > 1 {
                // 分数形式显示快门值（如 1/500）
                valueLabel.text = "快门: 1/\(Int(denominator.rounded()))秒"
            } else {
                // 如果是1秒
                valueLabel.text = "快门: 1秒"
            }
            
        case .whiteBalance:
            // 白平衡显示 - 符合用户直觉的描述
            let kelvin = 2500 + 5000 * Double(currentWhiteBalanceValue)
            
            // 基于色温添加描述性标签
            var wbDescription = ""
            if kelvin <= 3000 {
                wbDescription = "冷色调" // 低色温在用户直觉中是冷色调（偏蓝）
            } else if kelvin <= 4500 {
                wbDescription = "荧光灯"
            } else if kelvin <= 5500 {
                wbDescription = "日光"
            } else if kelvin <= 6500 {
                wbDescription = "阴天" 
            } else {
                wbDescription = "暖色调" // 高色温在用户直觉中是暖色调（偏黄/红）
            }
            
            valueLabel.text = "白平衡: \(Int(kelvin))K (\(wbDescription))"
            
        case .none:
            valueLabel.text = ""
        }
    }
    
    // MARK: - Actions
    
    @objc private func isoButtonTapped() {
        if activeControlMode == .iso {
            activeControlMode = .none
        } else {
            activeControlMode = .iso
        }
    }
    
    @objc private func shutterButtonTapped() {
        if activeControlMode == .shutterSpeed {
            activeControlMode = .none
        } else {
            activeControlMode = .shutterSpeed
        }
    }
    
    @objc private func whiteBalanceButtonTapped() {
        if activeControlMode == .whiteBalance {
            activeControlMode = .none
        } else {
            activeControlMode = .whiteBalance
        }
    }
    
    @objc private func sliderValueChanged(_ slider: UISlider) {
        switch activeControlMode {
        case .iso:
            currentISOValue = slider.value
            updateValueLabel(for: .iso)
            // 实时反馈 - 可选，但能提供更好的用户体验
            onISOValueChanged?(currentISOValue)
            
        case .shutterSpeed:
            currentShutterValue = slider.value
            updateValueLabel(for: .shutterSpeed)
            // 注意：快门值变化可能导致预览闪烁，建议仅在滑动结束时更新
            
        case .whiteBalance:
            currentWhiteBalanceValue = slider.value
            updateValueLabel(for: .whiteBalance)
            
            // 白平衡可以实时更新，不会导致相机画面闪烁
            onWhiteBalanceValueChanged?(currentWhiteBalanceValue)
            
        case .none:
            break
        }
    }
    
    @objc private func sliderTouchEnded(_ slider: UISlider) {
        // 当滑块调整结束时，触发回调
        switch activeControlMode {
        case .iso:
            onISOValueChanged?(currentISOValue)
            
        case .shutterSpeed:
            onShutterSpeedValueChanged?(currentShutterValue)
            
        case .whiteBalance:
            onWhiteBalanceValueChanged?(currentWhiteBalanceValue)
            
        case .none:
            break
        }
    }
} 